﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace BL
{
    public static class MessageHandling
    {
        private static dbDataContext db;


        public static dbDataContext Db
        {
            get
            {
                if (db == null)
                {
                    db = new dbDataContext();
                }
                return db;
            }
        }

        public static List<Message> GetMessages(tUser usr, tDevice dev)
        {
            String connectionString = "Data Source=85.230.217.230\\SQLEXPRESS,1433;Persist Security Info=True;User ID=thesis;Password=thesis";
            SqlConnection conn = null;
            SqlDataReader rdr = null;
            List<Message> lm = new List<Message>();

            try
            {

                conn = new SqlConnection(connectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("GetUnsentMessages", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@deviceId" ,dev.deviceId));
                rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Message m = new Message((int)rdr[0], (DateTime)rdr[1], (int)rdr[2], (string)rdr[3], usr, dev);
                    lm.Add(m);
                }
            }
            finally
            {
                if (conn != null)
                {
                    conn.Close();
                }
                if (rdr != null)
                {
                    rdr.Close();
                }
            }

            return lm;
        }

        public static void SetMessagesAsRead(List<Message> lm)
        {
            var deviceId = lm.First().DeviceId;

            foreach (IGrouping<int, Message> ig in lm.GroupBy(x => x.MessageTypeId))
            {
               var tdev = Db.tDeviceMessageTypes.Single(x => x.messageTypeId == ig.Key && x.deviceId == deviceId);
               tdev.lastSync = ig.Max(x => x.LastChange);
               Db.SubmitChanges();
            }

        }

        internal static void HandleIncommingMessage(string message)
        {

            int messageTypeId = int.Parse(message.Substring(0, 4));

            switch ((MessageType)messageTypeId)
            {
                case MessageType.UpdateStockBalance:
                    UpdateStockBalance.SaveMessage(message.Split(';'));
                    break;


            } 
            
            
        }

    }
}